package cn.hy.dataSync.statistics.container.communicator;


import cn.hy.dataSync.config.TaskConfig;
import cn.hy.dataSync.job.State;
import cn.hy.dataSync.statistics.communication.Communication;
import cn.hy.dataSync.statistics.container.collector.ProcessInnerCollector;
import org.apache.commons.lang.Validate;

import java.util.List;
import java.util.Map;

/**
 * 任务容器沟通者
 * 看来就是 job 中协调者，用来统领 全局，
 */
public abstract class AbstractTaskContainerCommunicator extends AbstractContainerCommunicator {

    protected String jobId;

    protected int taskId;

    public AbstractTaskContainerCommunicator(TaskConfig taskConfig) {
        super(taskConfig.getJobConfig());
        this.jobId = taskConfig.getJobConfig().getJobId();
        super.setCollector(new ProcessInnerCollector(this.jobId));
        this.taskId = taskConfig.getTaskId();
    }

    @Override
    public void registerCommunication(List<TaskConfig> taskConfigs) {
        super.getCollector().registerTaskCommunication(taskConfigs);
    }

    @Override
    public final Communication collect() {
        return this.getCollector().collectFromTask();
    }

    /**
     *  一次 job 中，全部任务（task）状态的，统计。
     *  (Failed | Killed) > Running > Success
     *  返回此次的任务的状态
     *
     * @return State
     */
    @Override
    public final State collectState() {
        Communication communication = new Communication();
        communication.setState(State.SUCCEEDED);

        for (Communication taskCommunication :
                super.getCollector().getTaskCommunicationMap().values()) {
            communication.mergeStateFrom(taskCommunication);
        }

        return communication.getState();
    }

    @Override
    public final Communication getCommunication(Integer taskId) {
        Validate.isTrue(taskId >= 0, "注册的 taskId 不能小于0");

        return super.getCollector().getTaskCommunication(taskId);
    }

    @Override
    public final Map<Integer, Communication> getCommunicationMap() {
        return super.getCollector().getTaskCommunicationMap();
    }
}
